﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SGArchiveSystem7xDB.Linq
{
    public  class T_SPFlowDal
    {
        static SGArchiveSystem7xEntities conn;
        public static List<V_SP> Get_SPFlow(out int count,int depid, int start = -1, int row = -1)
        {
            count = 0;
            try
            {
                conn = new SGArchiveSystem7xEntities();
                var query=  conn.V_SP.Select(c => c).Where(c => c.SPF_UserDep ==depid||c.SPF_AJDep==depid);
                query = query.Where(c => c.SPF_Status == 0);//0为未审批状态
                if (start != -1 && row != -1)
                {
                    count = query.Count();
                    return query.OrderBy(c => c.SPF_ID).Skip(start).Take(row).ToList();
                }
                else
                {
                    var list = query.ToList();
                    count = list.Count;
                    return list;
                }
            }
            catch(Exception ex)
            { return null; }
        }
        /// <summary>
        /// 审批流审批
        /// </summary>
        /// <param name="en"></param>
        /// <returns></returns>
        public static _ReturnValue SP_SPFlow(T_SPFlow en)//t_binfo里需要添加一个mj字段用于查询审批流
        {
            try
            {
                conn = new SGArchiveSystem7xEntities();
                var qu = conn.T_SPFlow.Select(c => c).Where(c => c.SPF_ID == en.SPF_ID);
                var bid = qu.Single().SPF_BID;
                var query = conn.T_BInfo.Select(c => c).Where(c => c.BI_ID == bid);
                var query1 = conn.V_BInfo.Select(c => c).Where(c => c.BI_ID == bid).Single();
                var user = conn.T_User.Select(c => c).Where(c => c.U_ID == query1.BU_BUSERID).Single();
                foreach (var nn in qu)
                {
                    nn.SPF_Result = en.SPF_Result;
                    nn.SPF_Status = en.SPF_Status;//已审批
                    nn.SPF_Suggest = en.SPF_Suggest;
                    nn.SPF_DATE = DateTime.Now;
                    nn.SPF_UID = en.SPF_UID;
                    nn.SPF_UNAME = en.SPF_UNAME;
                }
                conn.SaveChanges();
                var q = qu.Single();
                var flow= conn.T_SP.Select(c => c).Where(c => c.SP_ID == 1).Single();//目前默认取第一个，以后完善时根据密级来判断 
                string[] arr = flow.SP_STATUS.Split(',');
                if (en.SPF_Result == 1)//审批通过
                {
                    for (int i = (int)q.SPF_Stage; i < flow.SP_TOPLEVEL; i++)
                    {
                        if (i + 1 == flow.SP_TOPLEVEL)//这次流程已经为最后一次
                        {
                            if (arr[i] == "1")//最后流程需要审批（管理员）
                            {
                                ///把审批状态“流程中”改为“未审批”（t_binfo 中 BI_PSTATUS） 
                                foreach (var n in query)
                                {
                                    n.BI_SPSTATUS = (int)_BrrSPStatus._iStatus_未审批;
                                }
                                conn.SaveChanges();
                                int count = 0;
                                var listToMail = SGArchiveSystem7xDB.Linq.T_EmailDal.Get_Email(1, out count);
                                string[] email = new string[listToMail.Count()];
                                for (int n = 0; n < listToMail.Count(); n++)
                                {
                                    email[n] = listToMail[n].E_EMAIL;
                                }
                                SGArchiveSystem7xDB.Linq.T_BInfoDal.PrepareEmail("申请借阅", user.U_RNAME + "对档号为" + query1.BI_DH + "，题名为" + query1.BI_TM + "的档案发出了申请", email);
                                break;
                            }
                            else//不需要管理员审批，可以直接通过
                            {
                                ///把审批状态“流程中”改为“已审批”（t_binfo 中 BI_PSTATUS）审批结果为“同意”
                                string[] email = new string[1] { user.U_V01 };
                                T_BInfoDal.PrepareEmail("审批结果", "你对档案为" + query1.BI_DH + "题名为" + query1.BI_TM + "档案的申请已经通过", email);
                                foreach (var n in query)
                                {
                                    n.BI_SPDATE = DateTime.Now;
                                    n.BI_SPID = -1;//自动审批成功
                                    n.BI_SPNAME = "-1";//自动审批成功
                                    n.BI_SPVALUE = (int)_BrrSPValue._iValue_审批通过;
                                    n.BI_SPSTATUS = (int)_BrrSPStatus._iStatus_已审批;
                                    if (query1.BU_TYPE == (int)_BrrType._iType_电子借阅)
                                    {
                                        n.BI_LQDATE = DateTime.Now;
                                        n.BI_STATUS = (int)_BrrStatus._iStatus_借出;
                                    }
                                    if (query1.BU_TYPE == (int)_BrrType._iType_纸质借阅)
                                    {
                                        n.BI_STATUS = (int)_BrrStatus._iStatus_申请;
                                    }
                                }
                                conn.SaveChanges();
                                break;
                            }
                        }
                        else//不是最后一次
                        {
                            if (arr[i] == "1")//下一个流程是否要审批
                            {
                                SGArchiveSystem7xDB.T_SPFlow en1 = new SGArchiveSystem7xDB.T_SPFlow();
                                en1.SPF_UserDep = q.SPF_UserDep;
                                en1.SPF_AJDep = q.SPF_AJDep;
                                en1.SPF_BID = q.SPF_BID;
                                en1.SPF_Stage = i+1;//需要去T_SP表中查找需要审批的步骤，目前默认为1
                                en1.SPF_Status = 0;//还没审批
                                Add_SPFlow(en1, conn);
                                foreach (var n in query)
                                {
                                    n.BI_SPSTATUS = (i+2);
                                }
                                conn.SaveChanges();
                                var listEmail = SGArchiveSystem7xDB.Linq.T_UserDal.GET_EMAIL(q.SPF_AJDep, 1);
                                string[] email = new string[listEmail.Count()];
                                for (int n = 0; n < listEmail.Count(); n++)
                                {
                                    email[n] = listEmail[n].U_V01;
                                }
                                SGArchiveSystem7xDB.Linq.T_BInfoDal.PrepareEmail("申请借阅", user.U_RNAME + "对档号为" + query1.BI_DH + "，题名为" + query1.BI_TM + "的档案发出了申请", email);
                                break;
                            }
                        }
                    }
                }
                else//不通过 修改binfo 中字段‘BI_STATUS’为‘ 结束’ 若是纸质借阅，还需要修改aj的状态为‘在库’
                {                    
                    foreach (var n in query)
                    {
                        n.BI_STATUS = (int)_BrrStatus._iStatus_结束;
                    }
                    conn.SaveChanges();
                    if (query1.BU_TYPE == 2)
                    {
                        var query2 = conn.T_ArchiveAj.Select(c => c).Where(c => c.DH == query1.BI_DH);
                        foreach (var cn in query2)
                        {
                            cn.KFZT = (int)_ArchiveKFStatus._iStatus_在库;
                        }
                        conn.SaveChanges();
                    }
                    string[] email = new string[1] { user.U_V01 };
                    T_BInfoDal.PrepareEmail("审批结果", "你对档案为" + query1.BI_DH + "题名为" + query1.BI_TM + "档案的申请没有通过", email);
                }
                return _ReturnValue.OK;
            }
            catch(Exception ex)
            {
                return _ReturnValue.Err;
            }
        }
        public static int Add_SPFlow(T_SPFlow en)
        {
            try
            {
                conn = new SGArchiveSystem7xEntities();
                conn.T_SPFlow.Add(en);
                conn.SaveChanges();
                return en.SPF_ID;
            }
            catch (Exception ex)
            { return -1; }
        }

        public static int Add_SPFlow(T_SPFlow en, SGArchiveSystem7xEntities conn)
        {
            try
            {
                ////conn = new SGArchiveSystem7xEntities();
                conn.T_SPFlow.Add(en);
                conn.SaveChanges();
                return en.SPF_ID;
            }
            catch (Exception ex)
            { return -1; }
        }

        public static T_SP Get_SPContent()
        {
            try
            {
                conn = new SGArchiveSystem7xEntities();
                return conn.T_SP.Select(c => c).Where(c => c.SP_ID == 1).Single();
            }
            catch
            { return null; }
        }
        public static int Modify_SPContent(string status)
        {
            try
            {
                conn = new SGArchiveSystem7xEntities();
                var query = conn.T_SP.Select(c => c).Where(c => c.SP_ID == 1);
                foreach (var nn in query)
                {
                    nn.SP_STATUS = status;
                }
                conn.SaveChanges();
                return 1;
            }
            catch
            { return -1; }
        }
        public static V_SP Get_Brr(int id)
        {
            try
            {
                conn = new SGArchiveSystem7xEntities();
                var query = conn.V_SP.Select(c => c).Where(c => c.BI_ID == id).Single();
                return query;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}
